package com.liushuai.execlToWord;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.StyleDescription;
import org.apache.poi.hwpf.model.StyleSheet;
import org.apache.poi.hwpf.usermodel.CharacterProperties;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;


public class POIReportUtil {


    public static void main(String[] args) throws Exception {
        List<PersonInfo> listP=ReadExeclToData.readXls();
        for(int i=0;i<listP.size();i++) {
            PersonInfo pi=listP.get(i);
            Map<String, POIText> replaces = new HashMap<String, POIText>();
            System.out.println("导出数据：");

            replaces.put("${name}", POIText.str(pi.getPname()));

            replaces.put("${gs}", POIText.str(pi.getXb()));
            replaces.put("${bh}", POIText.str(pi.getZsbh()));


//        replaces.put("${graph2}", POIText.str("graph"));
//        replaces.put("${内容2}", POIText.str("2222"));
////
//        replaces.put("${graph3}", POIText.str("graph"));
//        replaces.put("${内容3}", POIText.str("33333"));
//
//
//        replaces.put("${graph4}", POIText.str("<END>"));
//        replaces.put("${内容4}", POIText.str(""));

//        for (int i=5;i<10;i++){
//            replaces.put("${graph"+i+"}", POIText.str(""));
//            replaces.put("${内容"+i+"}", POIText.str(""));
//        }


            HWPFDocument hwpf = poiWordTableReplace("C:\\Users\\Administrator\\Desktop\\template1.doc", replaces);
            FileOutputStream out = new FileOutputStream("c:\\test\\t"+(i+1)+".doc");
            hwpf.write(out);
            out.flush();
            out.close();

//            System.out.println("读入数据：");
//            FileInputStream in = new FileInputStream("c:\\t2.doc");
//            HWPFDocument hwpf2 = new HWPFDocument(in);
//            Map<String, String> map = readWord(hwpf2);
//            for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
//                java.util.Map.Entry entry = (java.util.Map.Entry) iter.next();
//                System.out.println(entry.getKey() + ":" + entry.getValue());
//            }
        }
    }

    public static Map<String, String> readWord(HWPFDocument hwpf
    ) throws Exception {
//        FileInputStream in = new FileInputStream(sourceFile);
//        HWPFDocument hwpf = new HWPFDocument(in);
        Map<String, String> oldMap = new HashMap<String, String>();
        Range r = hwpf.getRange();
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < r.numParagraphs(); i++) {
            Paragraph p = r.getParagraph(i);
            // check if style index is greater than total number of styles
            int numStyles = hwpf.getStyleSheet().numStyles();
            int styleIndex = p.getStyleIndex();
            if (numStyles > styleIndex) {
                StyleSheet style_sheet = hwpf.getStyleSheet();
                StyleDescription style = style_sheet.getStyleDescription(styleIndex);
                String styleName = style.getName();
                if (styleName != null && styleName.contains("标题 3")) {
                    // write style name and associated text
                    System.out.println(styleName + " -> " + p.text());
                    //System.out.println(p.text());
                    String text = p.text();
                    text = text.substring(0, text.length() - 1);
                    list.add(text);
                    oldMap.put(text, null);
                    if ("<END>".equals(text)) {
                        break;
                    }
                } else {
                    if (list.size() > 0) {
                        String key = list.get(list.size() - 1);
                        String oldS = oldMap.get(list.get(list.size() - 1));
                        String s = (p.text() == null) ? "" : p.text();
                        oldS = (oldS == null) ? s : (oldS + s);
                        if (oldS != null && oldS.trim().length() > 0) {
                            oldMap.put(key, oldS);
                        }
                    }
                }
            }
        }
        return oldMap;
    }

    public static HWPFDocument poiWordTableReplace(String sourceFile,
                                                   Map<String, POIText> replaces) throws Exception {
        FileInputStream in = new FileInputStream(sourceFile);
        HWPFDocument hwpf = new HWPFDocument(in);
//        Range range = hwpf.getRange();// 得到文档的读取范围
//        TableIterator it = new TableIterator(range);
//        // 迭代文档中的表格
//        while (it.hasNext()) {
//            Table tb = (Table) it.next();
//            // 迭代行，默认从0开始
//            for (int i = 0; i < tb.numRows(); i++) {
//                TableRow tr = tb.getRow(i);
//                // 迭代列，默认从0开始
//                for (int j = 0; j < tr.numCells(); j++) {
//                    TableCell td = tr.getCell(j);// 取得单元格
//                    // 取得单元格的内容
//                    for (int k = 0; k < td.numParagraphs(); k++) {
//                        Paragraph para = td.getParagraph(k);
//
//                        String s = para.text();
//                        final String old = s;
//                        for (String key : replaces.keySet()) {
//                            if (s.contains(key)) {
//                                s = s.replace(key, replaces.get(key).getText());
//                            }
//                        }
//                        if (!old.equals(s)) {// 有变化
//                            para.replaceText(old, s);
//                            s = para.text();
//                            System.out.println("old:" + old + "->" + "s:" + s);
//                        }
//
//                    } // end for
//                } // end for
//            } // end for
//        } // end while


        Range r = hwpf.getRange();
        CharacterProperties props = new CharacterProperties();
        props.setFontSize(10);
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < r.numParagraphs(); i++) {
            Paragraph p = r.getParagraph(i);
            // check if style index is greater than total number of styles
            int numStyles = hwpf.getStyleSheet().numStyles();
            int styleIndex = p.getStyleIndex();
            if (numStyles > styleIndex) {
                StyleSheet style_sheet = hwpf.getStyleSheet();
                StyleDescription style = style_sheet.getStyleDescription(styleIndex);
                String styleName = style.getName();
//                if (styleName!=null&&styleName.contains("标题")) {
//                    // write style name and associated text
//                    //System.out.println(styleName + " -> " + p.text());
//                    System.out.println(p.text());
//                    String text = p.text();
//                    list.add(text);
//                }else{
//                    System.out.println(  p.text());
//                }

                System.out.println(styleName);

                String s = p.text();
                final String old = s;
                for (String key : replaces.keySet()) {
                    if (s.contains(key)) {
                        s = s.replace(key, replaces.get(key).getText());
                    }
                }
                if (!old.equals(s)) {// 有变化
                    p.replaceText(old, s);
                    s = p.text();
                    System.out.println("old:" + old + "->" + "s:" + s);
                }


            }
        }
        return hwpf;
    }

}